//
//  GroupSearchBleListView.m
//  sentorise
//
//  Created by admin on 2025/9/16.
//

#import "GroupSearchBleListView.h"
#import "GlobalDefine.h"
#import "ProgressHUD.h"
#import "BlutoothGroupModel.h"
#import "DeviceSearchItemTableViewCell.h"

@interface GroupSearchBleListView()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *descLabel;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

@property (nonatomic, strong) BTManager *btManager;
@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *dataSource;
@property (nonatomic, strong) NSMutableArray<NSString *> *selectNames;
@property (nonatomic, strong) NSMutableDictionary *diviceNameDict;

@end

@implementation GroupSearchBleListView

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.titleLabel.text = NSLocalizedString(@"Set up battery syste", nil);
    self.descLabel.text = NSLocalizedString(@"Warm reminder: Only batteries with the same model as the current battery system are supported.", nil);
    [self.submitBtn setTitle:NSLocalizedString(@"Submit", nil) forState:UIControlStateNormal];

    self.btManager = [BTManager sharedBTManager];
    self.dataSource = [[NSMutableArray alloc] init];
    self.selectNames = [[NSMutableArray alloc] init];
    self.diviceNameDict = [[NSMutableDictionary alloc] init];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"DeviceSearchItemTableViewCell" bundle:nil] forCellReuseIdentifier:@"DeviceSearchItemTableViewCell"];
    
    [[BTManager sharedBTManager] retartScan];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevices:) name:kBTSearchDevices object:nil];
}

- (void)setBleNames:(NSArray *)bleNames {
    _bleNames = bleNames;
    [self.selectNames addObjectsFromArray:self.bleNames];
    [self.tableView reloadData];
}

- (IBAction)actionClose:(id)sender {
    [self removeFromSuperview];
}

- (IBAction)actionDown:(id)sender {
    if (!self.selectNames.count) {
        [ProgressHUD showErrorMessage:NSLocalizedString(@"Please select Bluetooth", nil)];
        return;
    }
    NSMutableArray *arr = [NSMutableArray array];
    for (CBPeripheral *p in self.dataSource) {
        if ([self.selectNames containsObject:p.name]) {
            [arr addObject:p];
        }
    }
    self.clickDown(arr);
    [self removeFromSuperview];
}

- (void)searchDevicesName:(NSNotification *)nf {
    NSMutableDictionary *dict = nf.object;
    [self.diviceNameDict addEntriesFromDictionary:dict];
    [self.tableView reloadData];
}

- (void)searchDevices:(NSNotification *)nf {
    NSArray *list1 = nf.object;
    NSMutableArray *list = [NSMutableArray array];
    // 只能选择已添加到我的设备中的
    NSString *listStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"BatteryBluList"] ?: @"";
    if (listStr.length) {
        NSArray *dataArray = [BlutoothModel covertToModelList:listStr];
        for (BlutoothModel *m in dataArray) {
            for (CBPeripheral *p in list1) {
                if ([m.uuid isEqualToString:p.identifier.UUIDString]) {
                    [list addObject:p];
                    break;
                }
            }
        }
    }

    [self.dataSource removeAllObjects];
    // 获取所有组的蓝牙，过滤掉已经存在的
    NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
    NSMutableArray *array = [NSMutableArray array];
    if (groupStr.length) {
        NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
        for (BlutoothGroupModel *group in dataArray) {
            for (BlutoothModel *mode in group.bluList) {
                if (mode.name.length) {
                    [array addObject:mode.name];
                }
            }
        }
    }
    for (CBPeripheral *p in list) {
        if (![array containsObject:p.name] || [self.bleNames containsObject:p.name] || [self.tempDeleteName containsObject:p.name]) {
            [self.dataSource addObject:p];
        }
    }
    
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceSearchItemTableViewCell *cell = (DeviceSearchItemTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"DeviceSearchItemTableViewCell"];
    
    NSString *name = [self.diviceNameDict objectForKey:self.dataSource[indexPath.section].name];
    name = name.length>0 ? name : self.dataSource[indexPath.section].name;
    cell.nameLabel.text = name;
    cell.rightSpace.constant = 50;
    cell.selectIV.hidden = ![self.selectNames containsObject:self.dataSource[indexPath.section].name];
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section {
    return 16;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 16)];
    view.backgroundColor = [UIColor clearColor];
    
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.selectNames containsObject:self.dataSource[indexPath.section].name]) {
        [self.selectNames removeObject:self.dataSource[indexPath.section].name];
    }else {
        [self.selectNames addObject:self.dataSource[indexPath.section].name];
    }
    [self.tableView reloadData];
}


@end
